package org.icnmasjid.member.webapp.action;

import java.security.InvalidKeyException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.icnmasjid.member.Constants;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.PersonSubOrgRole;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.PersonManager;
import org.icnmasjid.member.util.CommonUtil;
import org.icnmasjid.member.util.DesEncrypter;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;

public class SelfSchoolRegistrationController extends BasePersonFormController {
    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }
    public SelfSchoolRegistrationController() {
        setCommandName("person");
        setCommandClass(Person.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        Person person = null;
        // check to see if this is an user who followed the email web link to come to this page
        String key = request.getParameter("passKey");
        if ( key != null ) {
        	if ( StringUtils.isNotBlank(key) ) {
        		String personId = new DesEncrypter(Constants.CRYPTO_KEY).decrypt(key);
        		if ( NumberUtils.isNumber(personId) ) {
        			person = personManager.getPerson(personId);
        		}
        	}
        }
        if ( person == null ) {
        	throw new InvalidKeyException("The key is invalid");
        }        
        return person;
    }
    
    
    
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
    	Map map = super.referenceData(request, command, errors);
    	if ( map == null ) {
    		map = new HashMap();
    	}
    	Person p = (Person)command;
    	map.put("students", p.getStudents("Student-2012"));
    	if ( p.getStudents("Student-2013").size() > 0 ) {
    		errors.reject("already.registered","It looks like you have already registered your kids for the year 2013-2014");
    		saveMessage(request, "It looks like you have already registered your kids for the year 2013-2014");
    		map.put("alreadyRegistered", "true");
    	}
    	return map;
	}    
	
	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception 
	{
		super.onBindAndValidate(request, command, errors);
    	if ( ((Person)command).getStudents("Student-2013").size() > 0 ) {
    		errors.reject("already.registered","It looks like you have already registered your kids for the year 2013-2014");
    		saveMessage(request, "It looks like you have already registered your kids for the year 2013-2014");
    		return;
    	}		
        if ( request.getParameterValues("selectedStudentsId") == null ) {
        	errors.reject("no.checkbox.selected", "Please select at least one checkbox");
        	saveMessage(request, "Please select at least one checkbox");
        }		
	}

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }
        // for each student save the new role with same sub org
        Person p = (Person)command;
        String[] ids = request.getParameterValues("selectedStudentsId");
        for ( Person student : p.getStudents("Student-2012") ) {
        	if ( CollectionUtils.arrayToList(ids).contains(student.getPersonId().toString()) ) {
        		PersonSubOrgRole psor = new PersonSubOrgRole();
        		psor.setPerson(student);
        		psor.setRole(getRoleManager().getRole("Student-2013"));
        		psor.setSubOrg(getNextSubOrg(student.getSubOrg("Student-2012"), student));
        		student.getPersonSubOrgRoles().add(psor);
        		getPersonManager().savePerson(student);
        	}
        	
        }
        try {
	        CommonUtil.send(
	        	"registrations@icnschool.com",
	        	p.getEmails().toArray(new String[]{}), 
	        	new String[]{"registrations@icnschool.com"},
	        	"ICN Weekend School 2013-2014 Registration",
	        	getText(
						"email.content.registration.success",
						new Object[] {
							p.getFirstName(),
							p.getLastName()
						}
						, request.getLocale()
				)
	        );
        }catch (Exception e) {
        	System.out.println(e);
        	e.printStackTrace();
        }
        return new ModelAndView("successRegistrationRestricted");
    }
    
    private SubOrg getNextSubOrg(SubOrg so, Person student) {    	
    	if ( so.getName().matches("PreK-.*") ) {
    		return findSubOrg(so.getName().replaceAll("PreK-", "KG "));
    	}
    	if ( so.getName().matches("KG .*") ) {
    		return findSubOrg(so.getName().replaceAll("KG ", "1st Grade-"));
    	}
    	if ( so.getName().matches("1st.*") ) {
    		return findSubOrg(so.getName().replaceAll("1st", "2nd"));
    	}
    	if ( so.getName().matches("2nd.*") ) {
    		return findSubOrg(so.getName().replaceAll("2nd", "3rd"));
    	}
    	if ( so.getName().matches("3rd.*") ) {
    		return findSubOrg(so.getName().replaceAll("3rd", "4th"));
    	}
    	if ( so.getName().matches("4th.*") ) {
    		return findSubOrg(so.getName().replaceAll("4th", "5th"));
    	}
    	if ( so.getName().matches("5th.*") ) {
    		return findSubOrg(so.getName().replaceAll("5th", "6th"));
    	}
    	if ( so.getName().matches("6th.*") ) {
    		return findSubOrg("7th Grade-Section 1");
    	}
    	if ( so.getName().matches("7th.*") ) {
    		if ( "M".equals(student.getGender()) ) {
    			return findSubOrg("Youth-Program-Boys");
    		} else {
    			return findSubOrg("Youth-Program-Girls");
    		}
    	}
    	if ( so.getName().matches("Youth-Program-Boys") ) {
    		return findSubOrg("Youth-Program-Accelerated");
    	}
    	if ( so.getName().matches("Youth-Program-Girls") ) {
    		return findSubOrg("Youth-Program-Accelerated");
    	}
    	if ( so.getName().matches("Youth-Program-Accelerated") ) {
    		return so;
    	}
    	return null;
    }
    
    private SubOrg findSubOrg(String name) {
    	List<SubOrg> sos = getRoleManager().getSubOrgs();
    	for ( SubOrg so : sos ) {
    		if ( so.getName().equalsIgnoreCase(name) ) {
    			return so;
    		}
    	}
    	return null;
    }
}
